﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using WebFirst.Entities;

namespace Jn698._45Tool.Utils
{
    internal class XmlHelper
    {
        public static void Serializer<T>(string file,T t)
        {
            Stream stream = new FileStream(file, FileMode.Create);
            using (XmlWriter xmlWriter = new XmlTextWriter(stream,Encoding.Unicode))
            {
                new XmlSerializer(typeof(T)).Serialize(xmlWriter, t);
            }
        }

        public static T Deserializer<T>(string file)
        {
            var xml = File.ReadAllText(file);
            using (StringReader reader = new StringReader(xml))
            {
                var model = new XmlSerializer(typeof(T)).Deserialize(reader);
                return (T)model;
            }
        }

        public static void ExportToXml<T>(List<T> data, string filePath)
        {
            /*XDocument doc = new XDocument(
                new XElement("data",
                    data.Select(item => new XElement("item", item))
                )
            );
            doc.Save(filePath);*/

            using (System.IO.StringWriter stringWriter = new StringWriter(new StringBuilder()))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<T>));
                xmlSerializer.Serialize(stringWriter, data);
                FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate);
                StreamWriter sw = new StreamWriter(fs);
                sw.Write(stringWriter.ToString());
                sw.Close();
                fs.Close();
                //MessageBox.Show("写入文件成功！");
            }
        }

        public static List<T> LoadItemsFromXml<T>(string xmlFilePath)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
            using (StreamReader reader = new StreamReader(xmlFilePath))
            {
                return (List<T>)serializer.Deserialize(reader);
            }
        }

        /*public List<T> ImportFromXml<T>(string filePath)
        {
            XDocument doc = XDocument.Load(filePath);
            return doc.Element("data").Elements("item").Select(e => e.ToObject<T>()).ToList();
        }*/


    }
}
